package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.dialog.LoadingDialog;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.activity.OrderDetailActivity;
import com.jp.knowledge.my.adapter.OrderAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.MessageModel;
import com.jp.knowledge.my.model.OrderModel;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.ResultSubscriber;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 528787067@qq.com on 2017/5/4.
 */

public class OrderFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, ResultSubscriber.OnResultListener, CanRefreshLayout.OnLoadMoreListener {

    private static final int REFRESH_ORDER_LIST_CODE = 0x01;
    private static final int LOAD_MODE_ORDER_LIST_CODE = 0x02;
    private static final int ORDER_CANCEL = 0x03;
    private static final int ORDER_RECEIPT = 0x04;
    private static final int ORDER_DETAIL_CODE = 0x05;

    private CommDialog orderCancelDialog;

    public static OrderFragment newInstance(int orderStatus){
        OrderFragment orderFragment = new OrderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("orderStatus", orderStatus);
        orderFragment.setArguments(bundle);
        return orderFragment;
    }

    private Context mContext;
    private int orderStatus;
    private View contentView;
    private CanRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    private int page;
    private OrderAdapter adapter;
    private List<OrderModel> orderModels;

    private String cachePath;
    private FileCacheManager cacheManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        Bundle bundle = getArguments();
        this.orderStatus =  bundle.getInt("orderStatus");
        this.page = 1;

        cachePath = mContext.getCacheDir() + "/order_" + orderStatus;
        if(application.getUserData() != null)
            cachePath += ("_" + application.getUserData().getUuid());
        cachePath += ".dat";
        cacheManager = new FileCacheManager();

        orderCancelDialog = new CommDialog(mContext);
        orderCancelDialog.setContent("是否取消订单");
        orderCancelDialog.setTag(0);
        orderCancelDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) orderCancelDialog.getTag();
                JsonObject param = new JsonObject();
                param.addProperty("orderId", orderModels.get(position).getOrderId());
                HttpHelper.getInstance(mContext).orderCancel(param, position * 10 + ORDER_CANCEL, OrderFragment.this);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null){
            contentView = View.inflate(mContext, R.layout.refresh_recycleview, null);

            refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
            recyclerView = (RecyclerView) contentView.findViewById(R.id.can_content_view);

            refreshLayout.setOnRefreshListener(this);
            refreshLayout.setOnLoadMoreListener(this);

            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            orderModels = new ArrayList<>();
            adapter = new OrderAdapter(mContext, orderModels);
            recyclerView.setAdapter(adapter);
//            adapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
//                @Override
//                public void itemSelect(int position) {
//                    startActivityForResult(new Intent(mContext, OrderDetailActivity.class)
//                            .putExtra("data", (Serializable) orderModels)
//                            .putExtra("position", position), ORDER_DETAIL_CODE);
//                }
//            });
            adapter.setOrderBtnClickListener(new OrderAdapter.OrderBtnClickListener() {
                @Override
                public void onOrderPay(int position) {

                }
                @Override
                public void onOrderCancel(int position) {
                    orderCancelDialog.setTag(position);
                    orderCancelDialog.show();
                }
                @Override
                public void onOrderRefunds(int position) {

                }
                @Override
                public void onOrderReceipt(int position) {
                    JsonObject param = new JsonObject();
                    param.addProperty("orderId", orderModels.get(position).getOrderId());
                    HttpHelper.getInstance(mContext).orderReceipt(param, position *10 + ORDER_RECEIPT, OrderFragment.this);
                }
            });

            readCache();
        }
        return contentView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == ORDER_DETAIL_CODE && resultCode == RESULT_OK && data != null){
            int position = data.getIntExtra("position", -1);
            OrderModel orderModel = (OrderModel) data.getSerializableExtra("data");
            if(position != -1 && orderModel != null) {
                orderModels.remove(position);
                orderModels.add(position, orderModel);
                adapter.notifyItemChanged(position);
            }
        }
    }

    @Override
    public void onDestroy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(orderModels, cachePath);
            }
        }).start();
        super.onDestroy();
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<OrderModel>>() {
            @Override
            public void call(Subscriber<? super List<OrderModel>> subscriber) {
                List<OrderModel> data = (List<OrderModel>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<OrderModel>>() {
            @Override
            public void onCompleted() {
                refreshLayout.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<OrderModel> data) {
                if(data != null) {
                    orderModels = data;
                    adapter.updateAdapter(orderModels);
                }
                onCompleted();
            }
        });
    }

    private void getData(int page){
        JsonObject param = new JsonObject();
        param.addProperty("orderStatus", orderStatus);
        param.addProperty("page", page);
        HttpHelper.getInstance(mContext).getOrderList(param,
                (page == 1) ? REFRESH_ORDER_LIST_CODE : LOAD_MODE_ORDER_LIST_CODE, this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData(page);
    }

    @Override
    public void onLoadMore() {
        getData(++page);
    }

    @Override
    public void onStart(int requestType) {
        if(requestType%10 == ORDER_CANCEL || requestType%10 == ORDER_RECEIPT)
            loadingDialog.show();
    }
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_ORDER_LIST_CODE)
            refreshLayout.refreshComplete();
        else if(requestType == LOAD_MODE_ORDER_LIST_CODE)
            refreshLayout.loadMoreComplete();
        else if(requestType%10 == ORDER_CANCEL || requestType%10 == ORDER_RECEIPT)
            loadingDialog.cancel();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            ToasUtil.toast(mContext, data.getMessage());
        } else if(requestType == REFRESH_ORDER_LIST_CODE || requestType == LOAD_MODE_ORDER_LIST_CODE){
            if(requestType == REFRESH_ORDER_LIST_CODE)
                orderModels.clear();
            List<OrderModel> tempList = data.getList(OrderModel.class);
            if(tempList != null && tempList.size() > 0)
                orderModels.addAll(tempList);
            adapter.updateAdapter(orderModels);
        } else if(requestType%10 == ORDER_CANCEL || requestType%10 == ORDER_RECEIPT){
            int position = requestType / 10;
            orderModels.get(position).setOrderState((requestType%10 == ORDER_CANCEL) ? 3 : 5);
            adapter.notifyItemChanged(position);
        }
    }
}
